package com.zsx.shopping.order.aop;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zsx.shopping.common.exception.NoPermissionException;
import com.zsx.shopping.common.session.UserVO;
import com.zsx.shopping.order.annotation.OrderPermissionCheck;
import com.zsx.shopping.order.entity.Order;
import com.zsx.shopping.order.interceptor.LoginInterceptor;
import com.zsx.shopping.order.mapper.OrderMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;

@Aspect
@Component
public class OrderPermissionCheckAop {

    @Resource
    private OrderMapper orderMapper;

    @Before("@annotation(orderPermissionCheck)")
    void receiveAddressAuthorityCheck(JoinPoint point, OrderPermissionCheck orderPermissionCheck) {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        LocalVariableTableParameterNameDiscoverer localVariableTable = new LocalVariableTableParameterNameDiscoverer();
        String[] paramNameArr = localVariableTable.getParameterNames(method);
        if (paramNameArr != null) {
            Object[] args = point.getArgs();
            String idParamName = orderPermissionCheck.id();
            String snParamName = orderPermissionCheck.sn();
            UserVO userVO = LoginInterceptor.loginUser.get();
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<Order>().select(Order::getUserId);
            for (int i = 0; i < paramNameArr.length; i++) {
                if (paramNameArr[i].equals(idParamName)) {
                    queryWrapper.eq(Order::getId, args[i]);
                } else if (paramNameArr[i].equals(snParamName)) {
                    queryWrapper.eq(Order::getOrderSn, args[i]);
                }
            }
            Order order = orderMapper.selectOne(queryWrapper);
            if (order == null || !userVO.getId().equals(order.getUserId())) {
                throw new NoPermissionException();
            }
        }
    }
}
